package fm.huanxin.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import fm.cache.ConfigCache;
import fm.exception.BizException;
import fm.huanxin.utils.TokenUtils;
import fm.util.DateUtils;
import fm.util.RequestUtils;
import io.swagger.client.api.ChatHistoryApi;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 聊天记录数据同步定时任务
 * 环信API ：可以获取一小时前的聊天记录
 * 任务每小时 30 分执行一次 获取上一个小时的数据
 * Created by CM on 17/6/2.
 */
@Component
public class ChatHistoryAsyncTask {
    private static final Logger LOGGER = LoggerFactory.getLogger(ChatHistoryAsyncTask.class);

    public void run() {
        try {
            String orgName = ConfigCache.getConfig("HUANXIN_ORGNAME");
            String appName = ConfigCache.getConfig("HUANXIN_APPNAME");
            String clientId = ConfigCache.getConfig("HUANXIN_CLIENT_ID");
            String clientSecret = ConfigCache.getConfig("HUANXIN_CLIENT_SECRET");


            if (StringUtils.isEmpty(orgName) || StringUtils.isEmpty(appName) || StringUtils.isEmpty(clientId)
                    || StringUtils.isEmpty(clientSecret)) {
                throw new BizException("环信相关参数未配置,聊天记录同步任务执行失败!");
            }


            ChatHistoryApi api = new ChatHistoryApi();
            Date date = DateUtils.addHour(new Date(), -1);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH");

            String dateStr = sdf.format(date);
            String result = api.orgNameAppNameChatmessagesTimeGet(orgName, appName, TokenUtils.getAccessToken(), dateStr);

            LOGGER.info("环信返回:{}", result);
            if (StringUtils.isNotEmpty(result)) {
                JSONObject object = JSON.parseObject(result);
                String uri = object.getString("uri");
                String filePath = "/Users/apple/Desktop/wechat_yiche_websit/wechat-website/common/chathistory/" + dateStr + ".txt";
                RequestUtils.httpRequestFile(uri, filePath, null);
                String file = FileUtils.readFileToString(new File(filePath));

                JSONObject historyObject = JSON.parseObject(file);

                JSONArray history = historyObject.getJSONArray("entities");
                while (history.iterator().hasNext()) {
                    Object item = history.iterator().next();
                }
            } else {
                throw new BizException(dateStr + "-->聊天记录文件获取失败,返回为空");
            }

        } catch (Exception ex) {
            LOGGER.error("聊天记录同步任务执行失败", ex);
        }
    }


}
